package com.hengyi.pda;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.common.broadcastRecever.ScanDataBroadcastReceiver;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.DataCenter;
import com.common.retrofit.ShuangTu.QueryResultBean;
import com.common.retrofit.base.ShuangTuMethods;
import com.common.retrofit.service.ShuangTuService;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.utils.EmptyUtils;
import com.common.utils.LogUtils;
import com.common.utils.SPUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.hengyi.pda.activity.ModiFyNumActivity;
import com.hengyi.pda.activity.ScanBagsIntrueActivity;
import com.hengyi.pda.activity.Tes;
import com.hengyi.pda.submitjson.SheetSubmitBean;

import java.util.Iterator;
import java.util.TreeSet;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observable;
import rx.internal.operators.EmptyObservableHolder;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

public class MainPdaActivity extends BaseMvpActivity {
    @BindView(R.id.tv_scan)
    TextView tvScan;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_quary)
    TextView tvQuary;
    @BindView(R.id.tv_modify_num)
    TextView tv_modify_num;


    private ScanDataBroadcastReceiver scanDataBroadcastReceiver;
//    private ScanBroadcastReceiver scanBroadcastReceiver; // 新的

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main_pda;
    }

    @Override
    protected void onViewCreated() {

    }

    @Override
    protected void doLogicFunc() {
        getToken();
        attachClickListener(tvScan);
        attachClickListener(tvQuary);
        attachClickListener(tv_modify_num);

   /*         TreeSet tree = new TreeSet();
            tree.add("China");
            tree.add("China");
            tree.add("America");
            tree.add("Japan");
            tree.add("Chinese");
            Iterator iter = tree.iterator();
            while(iter.hasNext())
            {
                System.out.println("-------"+iter.next()+"------");
            }*/


    /*     scanBroadcastReceiver = new ScanBroadcastReceiver(new ScanBroadcastReceiver.PdaCallBack() {
            @Override
            public void setinfo(String s) {
                if (isAccept){
                    showToastMsg(s);
                }else {
                    showToastMsg(isAccept+"");
                }
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction("techain.intent.action.DISPLAY_SCAN_RESULT");
        registerReceiver(scanBroadcastReceiver, filter);*/
        //old
        openScanEnable();
        scanOutputDisable();
        scanDataBroadcastReceiver = new ScanDataBroadcastReceiver(new ScanDataBroadcastReceiver.PdaCallBack() {
            @Override
            public void setinfo(String s) {
                if (isAccept){
                    if(EmptyUtils.isNotEmpty(s)){
                        if(s.contains("http")){
                            Intent intent= new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                            Uri content_url = Uri.parse(s);
                            intent.setData(content_url);
                          startActivity(intent);
                        }else {
                            String aaa = s.substring(s.length() - 8, s.length());
//                            showToastMsg(aaa);
                            etCode.setText(aaa);
                            gotoQuery();
//                            showToastMsg(s);
                        }
                    }
                }
//                    showToastMsg(s);
            }
        });
        setScanReceiver(scanDataBroadcastReceiver);
    }

    private void getToken() {

        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                String token = (String) o;
//                showToastMsg(token);
                SPUtils.setShareString(DataCenter.TOKEN, token);
                DataCenter.getInstance().setToken(token);

            }

            @Override
            public void onError(String e, int code) {

                showToastMsg(e);
            }
        });

        JsonObject obj = new JsonObject();

        obj.addProperty("id", "sap-test");
        obj.addProperty("password", "sap-test-password");


        String route = new Gson().toJson(obj);
        System.out.println("aaaa" + route);
        LogUtils.e(route);
        RequestBody body = RequestBody.create(MediaType.parse("text/plan; charset=utf-8"), route);
        Observable observable = ShuangTuMethods.getRetrofitToken("http://192.168.0.249:9998/api/").create(ShuangTuService.class).
                auth(body);
        ShuangTuMethods.getInstance().toOtherSubscribe(observable, subscriber);
        rxManager.add(subscriber);
    }

    @Override
    protected void onViewClicked(View view) {
        if (view.getId() == tvScan.getId()) {
            //开启扫描
   /*         if (EmptyUtils.isNotEmpty(scanBroadcastReceiver)) {
                openScan();
                showToastMsg("代开");
//                setScanReceiver(scanDataBroadcastReceiver);
            }*/
            if (EmptyUtils.isNotEmpty(scanDataBroadcastReceiver)) {
//                openScan();
//                showToastMsg("代开");
                setScanReceiver(scanDataBroadcastReceiver);
            }
        } else if (view.getId() == tvQuary.getId()) {
            if(EmptyUtils.isEmpty(getEditTextStr(etCode))){
                showToastMsg("请输入码单号！");
            }
            String a = SPUtils.getShareString(getEditTextStr(etCode) + "submit");
            String b = SPUtils.getShareString(getEditTextStr(etCode) + "query");
            String ab = a+"" +
                    "\n"+b;
            Intent intent = new Intent(context, Tes.class);
            intent.putExtra(Tes.INFO,ab);
            startActivity(intent);
//            gotoQuery();
        } else if (view.getId() == tv_modify_num.getId()) {
            gotoActivity(ModiFyNumActivity.class);
        }
    }

    private void gotoQuery() {
        showProgressingDialog();
        CommonSubscriber<QueryResultBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                final QueryResultBean bean = (QueryResultBean) o;
                if(EmptyUtils.isNotEmpty(bean)&&EmptyUtils.isNotEmpty(bean.exports)&&bean.exports.E_RETURN.equals("1")){
                    showTwoDialog("核实调拨单号？", "客户："+bean.tables.T_DELIVERY_HEAD.get(0).CUSTOMER_NAME+"\n"+
                                    "车牌号码："+bean.tables.T_DELIVERY_HEAD.get(0).CAR_PLATE+"\n"
                                    +
                                    "调拨单号码："+bean.tables.T_DELIVERY_DETAIL.get(0).DELIVERY_BILL+"\n"

                            , "取消", "确认");
                    setOnDialogViewClick(new OnDialogViewClick() {
                        @Override
                        public void leftViewClick() {  // 左边

                        }

                        @Override
                        public void rightViewClick() { // 右边
                            if(EmptyUtils.isNotEmpty(SPUtils.getShareString("00"+getEditTextStr(etCode)+"query"))){
                                Intent intent = new Intent(context, ScanBagsIntrueActivity.class);
//                                intent.putExtra(ScanBagsIntrueActivity.BEAN,bean);
                                intent.putExtra(ScanBagsIntrueActivity.MADANNUM,"00"+getEditTextStr(etCode));
                                startActivity(intent);
                            }else {
                                Intent intent = new Intent(context, ScanBagsIntrueActivity.class);
                                intent.putExtra(ScanBagsIntrueActivity.BEAN,bean);
                                intent.putExtra(ScanBagsIntrueActivity.MADANNUM,"00"+getEditTextStr(etCode));
                                startActivity(intent);
                            }




                        }
                    });
                }else {
                    showToastMsg(bean.exports.E_MESSAGE);
                }






            }

            @Override
            public void onError(String e, int code) {
                    dismissProgressDialog();
                showToastMsg(e);
            }
        });

 /*       JsonObject obj = new JsonObject();

        obj.addProperty("id", "test");
        obj.addProperty("password", "test");


        String route = new Gson().toJson(obj);
        System.out.println("aaaa" + route);
        LogUtils.e(route);*/

        SheetSubmitBean bean = new SheetSubmitBean();
        SheetSubmitBean.ImportsBean childbean = new SheetSubmitBean.ImportsBean();
        childbean.I_DELIVERY_BILL = "00"+getEditTextStr(etCode);

        bean.imports = childbean;
        String route= new Gson().toJson(bean);
        LogUtils.e(route);
        RequestBody body = RequestBody.create(MediaType.parse("text/plan; charset=utf-8"), route);
        Observable observable = ShuangTuMethods.getRetrofit("rfcs/").create(ShuangTuService.class).
                ZHY_FN_ST_MARK_BARCODE_NOTICE(body);
        ShuangTuMethods.getInstance().toOtherSubscribe(observable, subscriber);
        rxManager.add(subscriber);
    }



    @Override
    protected void setNavigation() {
        super.setNavigation();


    }

    /**
     * 按两次返回键退出
     */
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToastMsg("再按一次退出" + getString(R.string.app_name));
                exitTime = System.currentTimeMillis();
                return true;
            } else {
                onBackPressed();
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
/*        if(scanBroadcastReceiver!=null)
            unregisterReceiver(scanBroadcastReceiver);*/
    }

    @Override
    protected void onResume() {
        super.onResume();
        System.out.println("kkkkkkll---");
        getToken();
    }
}
